#include "CPanelWidget.h"
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPaintEvent>
#include <QStyleOption>
#include <QPainter>

#include "global.h"
class CPanelWidget::CPanelWidgetPrivate
{
public:
    QWidget *header;
    QPushButton *btn_left;
    QPushButton *btn_right;
    QLabel *title;

    QWidget *content;

    CPanelWidgetPrivate(QWidget *parent)
        : header(new QWidget(parent)),
          btn_left(new QPushButton(parent)),
          btn_right(new QPushButton(parent)),
          title(new QLabel(parent)),
          content(new QWidget(parent))
    {
        OBJECTNAME(header);
        OBJECTNAME(btn_left);
        OBJECTNAME(btn_right);
        OBJECTNAME(title);
        OBJECTNAME(content);
    }
};

CPanelWidget::CPanelWidget(QWidget *parent)
    : p_(new CPanelWidgetPrivate(this))
{
    // layout
    QHBoxLayout *lay1 = new QHBoxLayout;
    lay1->addWidget(p_->btn_left, 0);
    lay1->addWidget(p_->title, 1);
    lay1->addWidget(p_->btn_right, 0);
    lay1->setSpacing(0);
    lay1->setMargin(0);
    p_->header->setLayout(lay1);
    p_->header->setMaximumHeight(40);
    p_->title->setScaledContents(true);

    QVBoxLayout *lay2 = new QVBoxLayout;
    lay2->addWidget(p_->header, 0);
    lay2->addWidget(p_->content, 0);
    lay2->setSpacing(0);
    lay2->setMargin(0);
    setLayout(lay2);
    setAttribute(Qt::WA_StyledBackground);
}

CPanelWidget::~CPanelWidget()
{
    delete p_;
}

QAbstractButton *CPanelWidget::getHeaderButton(int index)
{
    switch (index)
    {
    case 0:
        return p_->btn_left;
    case 1:
        return p_->btn_right;
    default:
        return nullptr;
    }
}

QWidget *CPanelWidget::getHeader()
{
    return p_->header;
}

QWidget *CPanelWidget::getContent()
{
    return p_->content;
}

void CPanelWidget::setWindowTitle(const QString &title)
{
    p_->title->setText(title);
    QWidget::setWindowTitle(title);
}

void CPanelWidget::setTitleAlignment(Qt::Alignment align)
{
    p_->title->setAlignment(align);
}

void CPanelWidget::paintEvent(QPaintEvent *event)
{
    QStyleOption o;
    o.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &o, &p, this);
}